<template>
  <el-dialog width="1200px" :title="dialogTitle" :visible.sync="dialogVisible" @close="handleClose">
    <el-alert
      v-if="submitForm.id!==''"
      :closable="false"
      style="margin-bottom: 20px"
      type="warning"
    >客户不可修改</el-alert>
    <el-form
      ref="submitForm"
      v-loading="formLoading"
      :model="submitForm"
      :rules="submitFormRules"
      label-width="100px"
      label-position="right"
      class="submit-form"
    >
      <div class="info_group">
        <div class="info_section" />
        <div class="info_title">送货单信息</div>
      </div>
      <el-row>
        <el-col :span="8">
          <el-form-item label="送货单号" prop="shipmentNo">
            <el-input v-model="submitForm.shipmentNo" disabled placeholder="系统默认生成" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="送货日期" prop="shipmentDate">
            <el-date-picker
              v-model="submitForm.shipmentDate"
              style="width: 100%"
              type="date"
              placeholder="请选择送货日期"
              value-format="yyyy-MM-dd"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户" prop="customerId">
            <customer-query ref="customerQuery" v-model="submitForm.customerId" :disabled="submitForm.id!==''" @choose="handleChooseCustomer" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="送货方式" prop="shipmentType">
            <dict-select v-model="submitForm.shipmentType" dict-key="shipment_type" placeholder="请选择送货方式" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收件人名称" prop="recipientName">
            <el-input v-model="submitForm.recipientName" placeholder="请输入收件人名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收件人手机" prop="recipientPhoneNum">
            <el-input v-model="submitForm.recipientPhoneNum" placeholder="请输入收件人手机" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item v-if="submitForm.shipmentType==='1'||submitForm.shipmentType==='2'" label="承运商" prop="carrier">
            <el-input v-model="submitForm.carrier" placeholder="请输入承运商/快递/物流公司名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item v-if="submitForm.shipmentType==='1'||submitForm.shipmentType==='2'" label="物流单号" prop="trackingNo">
            <el-input v-model="submitForm.trackingNo" placeholder="请输入物流/快递单号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item v-if="submitForm.shipmentType==='1'||submitForm.shipmentType==='2'" label="运费" prop="shipCost">
            <el-input v-model="submitForm.shipCost" type="number" placeholder="请输入运费" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收件人地址" prop="recipientAddress">
            <el-input
              v-model="submitForm.recipientAddress"
              class="item"
              placeholder="请输入收件人地址"
              maxlength="100"
              show-word-limit
              type="textarea"
              :autosize="{ minRows: 2}"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="submitForm.remark"
              class="item"
              placeholder="请输入备注"
              maxlength="100"
              show-word-limit
              type="textarea"
              :autosize="{ minRows: 2}"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="info_group">
      <div class="info_section" />
      <div class="info_title">订单信息</div>
    </div>
    <el-table
      :data="submitForm.orderList"
      style="width: 100%"
      border
      @cell-mouse-enter="handleCellEnter"
      @cell-mouse-leave="handleCellLeave"
    >
      <!--          <el-table-column type="index" />-->
      <el-table-column label="订单编号" prop="orderNo" min-width="100">
        <template slot-scope="scope">
          {{ scope.row.orderNo }}
        </template>
      </el-table-column>
      <!--          <el-table-column label="产品名称" prop="productName" min-width="80" />-->
      <el-table-column label="产品名称" prop="productName" min-width="200">
        <template slot-scope="scope">
          {{ scope.row.productName }}
        </template>
      </el-table-column>
      <!--          <el-table-column label="产品属性" prop="productAttribute" min-width="220">
        <template slot-scope="scope">
          <el-row>
            <el-col v-for="(item,index) in scope.row.productAttribute" :key="index" :span="8">
              {{ item.name }}：{{ item.value }}
            </el-col>
          </el-row>
        </template>
      </el-table-column>-->
      <el-table-column label="总数量" min-width="70">
        <template slot-scope="scope">
          {{ scope.row.orderQuantity }}{{ scope.row.unit }}
        </template>
      </el-table-column>
      <el-table-column label="单价" prop="unitPrice" min-width="80">
        <template slot-scope="scope">
          <money-format v-model="scope.row.unitPrice" />
        </template>
      </el-table-column>
      <el-table-column label="金额" prop="amount" min-width="100">
        <template slot-scope="scope">
          <money-format v-model="scope.row.orderAmount" />
        </template>
      </el-table-column>
      <el-table-column label="剩余数量" min-width="70">
        <template slot-scope="scope">
          {{ scope.row.remainingQuantity }}{{ scope.row.unit }}
        </template>
      </el-table-column>
      <el-table-column label="送货数量" prop="quantity" min-width="80" style="background-color: #515a6e">
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model="scope.row.quantity"
            type="number"
            class="item"
            placeholder="请输入数量"
          />
          <div v-else class="txt">
            {{ scope.row.quantity }} {{ scope.row.unit }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" min-width="80">
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model="scope.row.remark"
            class="item"
            placeholder="请输入备注"
          />
          <div v-else class="txt">
            {{ scope.row.remark }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="40">
        <template slot-scope="scope">
          <el-button type="text" style="color: #EC6E69" class="el-icon-delete" @click="removeOrder(scope.row)" />
        </template>
      </el-table-column>
    </el-table>
    <el-button icon="el-icon-plus" plain style="width: 100%;" @click="showSaleOrder">添加订单</el-button>
    <span slot="footer" class="dialog-footer">
      <el-button :loading="formLoading" type="text" @click="handleClose">取消</el-button>
      <el-button :loading="formLoading" type="primary" @click="handleSubmit">提交</el-button>
    </span>
    <div v-if="orderVisible">
      <sale-order-module ref="orderModule" multiple :query="{customerId: submitForm.customerId,shipmentStateList: ['0','1']}" :visible="orderVisible" @close="closeOrderDialog" />
    </div>
  </el-dialog>
</template>

<script>
import { shipment_save, shipment_detail, shipment_update } from '@/api/sale/shipment'
import moment from 'moment'
import saleOrderModule from '@/modules/saleOrderModule.vue'

/**
 * @author yizuomin
 * @date 2023/5/7 19:05
 **/
export default {
  name: 'SubmitModule',
  components: { saleOrderModule },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      dialogTitle: '',
      formLoading: false,
      submitForm: {
        id: '',
        shipmentDate: moment(new Date()).format('YYYY-MM-DD'),
        customerId: '',
        quantity: '',
        shipmentType: '',
        carrier: '',
        trackingNo: '',
        shipCost: '',
        recipientName: '',
        recipientPhoneNum: '',
        recipientAddress: '',
        orderList: []
      },
      orderVisible: false,
      orderInfo: {},
      submitFormRules: {
        shipmentDate: [{ required: true, message: '请选择送货日期', trigger: 'change' }],
        customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
        quantity: [{ required: true, message: '请输入送货数量', trigger: 'change' }],
        shipmentType: [{ required: true, message: '请选择送货方式', trigger: 'change' }]
        // carrier: [{ required: true, message: '请输入承运商/快递/物流公司名称', trigger: 'change' }],
        // trackingNo: [{ required: true, message: '请输入物流跟踪号', trigger: 'change' }],
        // shipCost: [{ required: true, message: '请输入运费', trigger: 'change' }],
        // recipientName: [{ required: true, message: '请输入收件人名称', trigger: 'change' }],
        // recipientPhoneNum: [{ required: true, message: '请输入收件人手机', trigger: 'change' }],
        // recipientAddress: [{ required: true, message: '请输入收件人地址', trigger: 'change' }
      }
    }
  },
  methods: {
    init(id) {
      if (!id) {
        this.dialogTitle = '新增送货单'
        return
      }
      this.dialogTitle = '修改送货单'
      this.formLoading = true
      shipment_detail(id).then(resp => {
        if (resp.success) {
          resp.data.orderList.forEach(e => e.isEdit = false)
          this.$refs.customerQuery.init(resp.data.customerName)
          this.submitForm = resp.data
        }
      }).finally(() => {
        this.formLoading = false
      })
    },
    handleSubmit() {
      this.$refs.submitForm.validate((valid) => {
        if (valid) {
          if (this.submitForm.orderList.length === 0) {
            this.$message.error('请选择订单')
            return
          }
          for (let i = 0; i < this.submitForm.orderList.length; i++) {
            const order = this.submitForm.orderList[i]
            if (order.quantity <= 0) {
              this.$message.error(`请输入第${i + 1}行订单的送货数量`)
              return
            }
          }
          let request = shipment_save
          if (this.submitForm.id) {
            request = shipment_update
          }
          this.formLoading = true
          request(this.submitForm).then(resp => {
            if (resp.success) {
              this.$message.success('操作成功')
              this.$refs.submitForm.resetFields()
              this.handleClose()
            }
          }).finally(() => {
            this.formLoading = false
          })
        }
      })
    },
    handleClose() {
      this.$emit('close')
    },
    removeOrder(row) {
      this.$confirm('是否从订单列表中移除此订单', '移除提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.submitForm.orderList.splice(this.submitForm.orderList.indexOf(row), 1)
      })
    },
    showSaleOrder() {
      if (this.submitForm.customerId === '') {
        this.$message.error('请先选择客户')
        return
      }
      this.orderVisible = true
      this.$nextTick(() => {
        this.$refs.orderModule.doPage()
      })
    },
    closeOrderDialog(orderList) {
      this.orderVisible = false
      if (orderList && orderList.length > 0) {
        for (let i = 0; i < orderList.length; i++) {
          const row = orderList[i]
          row.orderQuantity = row.quantity
          row.orderAmount = row.amount
          row.quantity = 0
          row.orderId = row.id
          const customerIds = this.submitForm.orderList.map(e => e.customerId)
          const orderIds = this.submitForm.orderList.map(e => e.orderId)
          if (customerIds.length > 0 && customerIds.indexOf(row.customerId) === -1) {
            this.$message.error('只能选择相同客户的订单')
            return
          }
          if (orderIds.length > 0 && orderIds.indexOf(row.orderId) !== -1) {
            this.$message.error(`选择订单与第${orderIds.indexOf(row.orderId) + 1}条订单重复`)
            return
          }
          this.submitForm.orderList.push(row)
        }
      }
    },
    handleChooseCustomer(row) {
      if (row) {
        this.submitForm.customerId = row.id
        this.submitForm.recipientName = row.contacts
        this.submitForm.recipientPhoneNum = row.phoneNum
        this.submitForm.recipientAddress = row.address
      }
    },
    /** 鼠标移入cell */
    handleCellEnter(row, column, cell, event) {
      row.isEdit = true
    },
    /** 鼠标移出cell */
    handleCellLeave(row, column, cell, event) {
      row.isEdit = false
    }
  }
}
</script>

<style scoped>

</style>
